﻿using System;
using System.Globalization;

namespace Extensions {
    public static class DateTimeExtensions {
        public static int WeeksUntil(this DateTime dateTimeFrom, DateTime dateTimeTo) {
            return NumberOfWeeksFromCalendar(dateTimeFrom, dateTimeTo);
        }

        static int NumberOfWeeksFromCalendar(DateTime dateFrom, DateTime dateTo) {
            if (dateTo.Year == dateFrom.Year) { return WeeksInYear(dateTo) - WeeksInYear(dateFrom); }
            if (dateTo.Year - dateFrom.Year == 1) {
                int weeksInYear2 = WeeksInYear(dateTo) - WeeksInYear(new DateTime(dateTo.Year, 1, 1));
                int weeksInYear1 = WeeksInYear(new DateTime(dateFrom.Year, 12, 31)) - WeeksInYear(dateFrom);
                return weeksInYear1 + weeksInYear2;
            }
            throw new Exception("Dates more than 2 years apart not currently implemented");
        }
        
        static int WeeksInYear(DateTime targetDate) {
            var cal = new GregorianCalendar(GregorianCalendarTypes.Localized);
            int week = cal.GetWeekOfYear(targetDate, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
            return week;
        }
    }
}